﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using System.Data;

namespace PeisongWeb.admin
{
    public partial class productEdit : adminPage
    {
        protected int id
        {
            get
            {
                int tmp;
                try { tmp = Convert.ToInt32(ViewState["id"]); }
                catch { tmp = 0; }
                return tmp;
            }
            set
            { ViewState["id"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!IsPostBack)
                {

                    if (hasPermission("BC", 1))
                    {
                        if (Request.QueryString["product"] != null)
                        {
                            if (Library.Number.IsIntPositive(Request.QueryString["product"]))
                            {
                                id = Convert.ToInt32(Request.QueryString["product"]);
                            }
                        }

                        drpBind();
                        if (id != 0)
                        {

                            getDetails();
                        }
                        else
                        {
                            //liAutoPercent.Visible = true;
                        }
                    }
                    else
                    {
                        Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                        return;
                    }
                }



            }
        }

        private void getDetails()
        {

            ProductEntity pro = logic.product.getById(id);

            txt_ProductNo.Text = pro.ProductNo;

            txt_Name.Text = pro.Name;

            txt_Unit.Text = pro.Unit;

            txt_Standard.Text = pro.Standard;
            html_Details.SetValue(pro.Description);
            txt_AutoAdd.Text = hd_autoAdd.Value = string.Format("{0:F2}", pro.AutoAdd);
            drp_Type.SelectedIndex = drp_Type.Items.IndexOf(drp_Type.Items.FindByValue(pro.CategoryId.ToString()));
            html_StandardInfor.SetValue(pro.StandardInfor);

            cbx_IsSale.Checked = pro.IsSale;
            cbx_IsAutoPrice.Checked = pro.IsAutoPrice;
            cbx_IsCurrentPrice.Checked = pro.IsCurrentCost;
            DataTable dt = logic.files.getListByProduct(id);
            string str = "";
            foreach (DataRow dr in dt.Rows)
            {

                if (str != "")
                    str += "," + dr["filesid"].ToString() + "," + dr["Systemname"].ToString();
                else
                    str += dr["filesid"].ToString() + "," + dr["Systemname"].ToString();

            }

            hd_str.Value = str;
            hid_photolist.Value = str;






        }

        private void drpBind()
        {

            drp_Type.DataSource = logic.category.select("treelevel=1", "sort", 200, 1).Tables[1];// logic.category.list();
            drp_Type.DataTextField = "name";
            drp_Type.DataValueField = "categoryId";
            drp_Type.DataBind();
            drp_Type.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择类别--", ""));


            rpt_buyerRange.DataSource = logic.product.getBuyRange(id);
            rpt_buyerRange.DataBind();
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            if (logic.category.isExistShortname(id, txt_ProductNo.Text.Trim()))
            {
                Library.Script.ClientMsg("已经存在商品编号，请更换！");
                return;
            }

            ProductEntity pro = new ProductEntity();
            pro.ProductId = id;

            pro.ProductNo = txt_ProductNo.Text.Trim();
            pro.Name = txt_Name.Text;
            pro.Adminid = logic.sysAdmin.AdminID;
            pro.AutoAdd = Convert.ToDecimal(txt_AutoAdd.Text);
            pro.CategoryId = Convert.ToInt32(drp_Type.Value);
            pro.Description = html_Details.Value.ToString();
            pro.Standard = txt_Standard.Text;
            pro.Unit = txt_Unit.Text;
            pro.StandardInfor = html_StandardInfor.Value.ToString();
            pro.IsSale = cbx_IsSale.Checked;
            pro.IsAutoPrice = cbx_IsAutoPrice.Checked;
            pro.IsCurrentCost = cbx_IsCurrentPrice.Checked;

            if (id != 0)
            {
                //如果取消时价后,修改该商品前执行
                DAL.Product.productIsCurrentCancelProduct(pro.Adminid, id, pro.IsCurrentCost);


                logic.product.update(pro);

                //如果商品加价比例有修改，则增加采购商历史价格
                if (txt_AutoAdd.Text.Trim() != hd_autoAdd.Value && cbx_IsAutoPrice.Checked == true)
                {
                    logic.buyerPriceHistory.insertByUpdateProduct(id);
                }
               
                //创建图片文件
                updateFiles(id);
                string buyers = hd_buyers.Value.ToString();
                logic.buyerRange.insertByProductId(buyers, id);
            }
            else
            {
                int proId = logic.product.insert(pro);

                //增加企业价格体系
                //PriceStructureEntity ps = new PriceStructureEntity();

                //decimal autoPercent = 0m;
                //decimal.TryParse(txt_AutoPercent.Text, out autoPercent);
                //ps.AutoPercent = autoPercent;
                //ps.ProductId = proId;
                //ps.CategoryId = pro.CategoryId;
                //logic.priceStructure.insertByProduct(ps);


                //创建图片文件
                updateFiles(proId);
                string buyers = hd_buyers.Value.ToString();
                logic.buyerRange.insertByProductId(buyers, proId);
            }



            //Library.Script.ClientMsgUrl("保存成功！", "productList.aspx");
            Library.Script.RegisterStartup("javascript:alert('保存成功');winClose();");
        }

        void updateFiles(int proId)
        {
            string[] splitstr = { "," };
            string[] lists = hid_photolist.Value.Split(splitstr, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lists.Length; i = i + 2)
            {

                FilesEntity fl = new FilesEntity();
                fl.FilesId = Convert.ToInt32(lists[i]);
                fl.ProductId = proId;
                fl.IsIndex = i == 0 ? true : false; //判断第一个图片
                logic.files.update(fl);
            }
        }
    }
}
